<template>
  <MenuPage :data="FlowList" 
  :columns="flowCol"
  :page.sync="FlowPage"
  :size.sync="FlowPageSize"
  :total="FlowTotal"
  :loading="FlowListLoading"
  @queryFun="getFlowList">
    <template slot="search">
        <Button type="primary" ghost class="md-add-jh" @click="addFlowModal">创建{{pageBtnTxt}}</Button>
        <!-- <Divider type="vertical" style="margin: 10px 0px 10px 10px;"/>
                  <div style="height: 32px;line-height: 32px;margin-left: 15px">
                      <Checkbox v-model="creatByMeModal" @on-change="searchCreatedByMe" style="width: 70px;">由我创建</Checkbox>
                  </div> -->
        <Input
          clearable
          v-model.trim="FlowModelInput"
          placeholder="流量名称"
          @on-change="searchFlowNameBtn"
          style="width: 180px;margin-left: 15px"
        />
        <Button
          class="header-btn"
          type="primary"
          ghost
          style="height: 32px;margin-left: 5px;"
          @click="refreshFlow()"
        >
          <i class="el-icon-refresh-right" />
        </Button>
    </template>
          <Modal
            v-model="showModal"
            :mask-closable="false"
            width="500"
            :closable="false"
            :footer-hide="true"
            :title="title1"
          >
            <Form ref="formItem" :model="formItem" :rules="formItemRule" :label-width="80">
              <FormItem label="名称" prop="fileName">
                <Input v-model.trim="formItem.fileName" placeholder="名称长度为1—128个字符"></Input>
              </FormItem>
              <FormItem v-if="isAdd" label="上传文件" prop="file">
                <Upload
                  ref="uploadIcon"
                  :action="upLoadUrl"
                  :on-success="imprtQuesSucc"
                  :before-upload="handleUploadIcon"
                  :model="formItem.file"
                  style="display:inline-block;"
                >
                  <Button class="fr" type="primary" ghost icon="ios-cloud-upload-outline"
                    >选择文件</Button
                  >
                </Upload>
                <WarningTip
                  style="position: absolute;left: 104px;"
                  content="请上传pcap类型的文件"
                ></WarningTip>
              </FormItem>
              <FormItem label="描述" prop="note">
                <Input
                  v-model.trim="formItem.note"
                  type="textarea"
                  :maxlength="200"
                  :autosize="{ minRows: 2, maxRows: 5 }"
                  placeholder="描述"
                ></Input>
              </FormItem>
              <FormItem>
                <Button type="primary" @click="formBtn('formItem')" :loading="loading">确定</Button>
                <Button @click="cancelUpload()" style="margin-left: 8px">取消</Button>
              </FormItem>
            </Form>
          </Modal>
</MenuPage>
</template>

<script>
import $ from 'jquery';
import encryption from '@/libs/encryption.js';
import { getFlowData, modifyFlow, createFlow, delFlow } from '@/api/flow.js';
import { debounce } from '@/libs/utils';
import pageTitle from '@/mixin/pageTitle';
import {validateName1,validateNameCustom,newValidationRules,newValidationRulesTip } from '@/libs/reg.js'
export default {
  mixins: [pageTitle],
  components: {},
  data() {
    const validateUpload = (rule, value, callback) => {
      if (this.formItemRule.file === null) {
        callback(new Error('请选择文件'));
      } else {
        callback();
      }
    };
    const validateName = (rule, value, callback) => {
      if (value) {
        validateNameCustom(rule, value, callback, 128)
      } else {
        callback();
      }
    };
    return {
      // 用户信息
      USER_ID: '',
      isRootDesigner: '',
      // 页面设置
      fullHeight: document.documentElement.clientHeight,
      fullWidth: document.documentElement.clientWidth,
      setTableHei: 'auto',
      // 数据
      FlowList: [],
      FlowPage: 1,
      FlowPageSize: 10,
      FlowTotal: 0,
      selectFlowType: '',
      creatByMeModal: '',
      searchFlowName: '',
      FlowListLoading: true,
      FlowModelInput: '',
      flowCol: [
        {
            key:'fileName',
            title:'名称',
            tooltip:true,
        },
        {
          key:'minioPath',
          title:'路径',
          tooltip:true,
        },
        {
          key:'note',
          title:'描述',
          tooltip:true,
        },
        {
          key:'creatorName',
          title:'创建者',
          tooltip:true,
        },
        {
          key:'created',
          title:'创建时间',
          tooltip:true,
        },
        {
          title:'操作',
          key:'action',
          opList:[
            {
              txt:'修改',
              disabled:this.setIsClick,
              on:{
                click:(data) => {
                  this.modifyFlow1(data)
                }
              }
            },
            {
              type:'delete',
              txt:'删除',
              title:'确定要删除吗？',
              disabled:this.setIsClick,
              on:{
                click:(data,e) => {
                  this.delFlow(data)
                }
              },
              tooltip:true
            }
          ]
        }
      ],
      // 新列表
      showDataList: true,
      showDefImg: false,
      // 查看Flow
      bigFlowModal: false,
      showFlowSrc: '',
      showModal: false,
      isAdd: false,
      upLoadUrl: ``,
      loading: false,
      showSelectBucket: false,
      speed: 0,
      loaded: 0,
      fileSize: 0,
      progress: 0,
      uploadShow: false, //上次时关闭对话框提示
      updataLoading: true,
      isUpdataing: false, //判断是否在上传中
      title1: `创建${this.pageBtnTxt}`,
      formItem: {
        fileName: '',
        filePath: null,
        file: null,
        fileId: '',
        note: ''
      },
      formItemRule: {
        fileName: [
          { required: true, message: '名称不能为空', trigger: 'change' },
          { validator: validateName, trigger: 'change' }],
        file: [{ required: true, validator: validateUpload, trigger: 'change' }]
      }
    };
  },
  created() {
    // 获取用户id
    let November = sessionStorage.getItem('November');
    November = JSON.parse(encryption.SelfUseDecrypt(November));
    this.USER_ID = November.userId;
    this.isRootDesigner = November.isRootDesigner;
    this.upLoadUrl = `/api/minio/upload/permanent?visibility=company&type=pcap&bucket=pcap`;
  },
  mounted() {
    this.setStyle();
    window.onresize = () => {
      this.setStyle();
    };
    //赋值查询条件
    let queryObj = sessionStorage.getItem('queryObj');
    if (queryObj) {
      let params = JSON.parse(queryObj);
      this.FlowPage = params.pageIndex;
      this.FlowPageSize = params.pageSize;
      this.selectFlowType = params.visibility;
      this.searchFlowName = params.name;
      this.creatByMeModal = params.self;
      sessionStorage.removeItem('queryObj');
    }
    this.getFlowList();
  },
  methods: {
    // 设置高度
    setStyle() {
      window.fullHeight = document.documentElement.clientHeight;
      window.fullWidth = document.documentElement.clientWidth;
      this.fullHeight = window.fullHeight;
      this.fullWidth = window.fullWidth;
      this.setTableHei = this.fullHeight - 197;
      this.FlowPageSize = Math.floor(this.setTableHei / 96);
    },
    // Flow列表
    getFlowList: debounce(function() {
      let params = {
        pageIndex: this.FlowPage,
        pageSize: this.FlowPageSize,
        visibility: this.selectFlowType,
        fileName: this.searchFlowName,
        type: 'l7'
      };
      this.queryObj = JSON.stringify(params);
      getFlowData(params)
        .then((res) => {
          if (res.data.code == 1) {
            let pageList = res.data.data;
            this.FlowTotal = parseInt(pageList.total);
            this.FlowList = pageList.items;
          } else {
            this.FlowList = [];
            this.FlowTotal = 0;
          }
          this.FlowListLoading = false;
        })
        .catch((err) => {
          this.FlowListLoading = false;
          console.log(err);
        });
    }, 500),
    FlowOnChange(val) {
      this.FlowListLoading = true;
      this.FlowPage = val;
      this.getFlowList();
    },
    selectFlowTypeChange(val) {
      this.FlowPage = 1;
      this.selectFlowType = val;
      this.getFlowList();
    },
    searchCreatedByMe(val) {
      this.FlowPage = 1;
      this.getFlowList();
    },
    searchFlowNameBtn() {
      this.FlowPage = 1;
      this.searchFlowName = $.trim(this.FlowModelInput);
      this.getFlowList();
    },
    // 添加Flow
    addFlowModal() {
      this.showModal = true;
      this.loading = false;
      this.formItem.visibility = 'share';
      this.formItem.file = null;
      this.formItem.fileId = '';
      this.showSelectBucket = false;
      this.isAdd = true;
      this.title1 = `创建${this.pageBtnTxt}`;
      this.$nextTick(() => {
        this.$refs['uploadIcon'].clearFiles();
        this.$refs['formItem'].resetFields();
      });
    },
    // 修改Flow
    modifyFlow1(row) {
      this.showModal = true;
      this.loading = false;
      this.title1 = `修改${this.pageBtnTxt}`;
      this.isAdd = false;
      let params = Object.assign({}, row);
      this.formItem.fileName = params.fileName;
      this.formItem.id = params.id;
      this.formItem.note = params.note;
    },
    // 删除
    delFlow(id) {
      delFlow(id)
        .then((res) => {
          if (res.data.code == 1) {
            this.$Message.success({
              content: '删除成功！',
              duration: 3
            });
            this.FlowPage =
              this.FlowPage > 1 && this.FlowList.length === 1 ? this.FlowPage - 1 : this.FlowPage;
            this.getFlowList();
          } else {
            this.$Message.error(res.message);
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // 刷新Flow
    refreshFlow() {
      this.FlowPage = 1;
      this.searchFlowName = '';
      this.FlowModelInput = '';
      this.selectFlowType = '';
      this.creatByMeModal = false;
      this.getFlowList();
    },
    // 计算index
    handleProIndex(key) {
      return (this.FlowPage - 1) * this.FlowPageSize + key + 1;
    },
    // 设置可见范围
    setVisibility(val) {
      let obj = {};
      let text = '';
      let color = '';
      if (val === 'share') {
        text = '单位';
        color = '#32CD32';
      } else if (val === 'private') {
        text = '个人';
        color = '#FFA500';
      } else if (val === 'public') {
        text = '系统';
        color = '#4169E1';
      }
      obj.text = text;
      obj.color = color;
      return obj;
    },
    // 设置知否可点击
    setIsClick(item) {
      if (item.isshare === 'public' || (item.creator !== this.USER_ID && !this.isRootDesigner)) {
        return true //{ 'pointer-events': 'none' };
      }
    },
    setImgSrc(item) {
      if (item.isshare === 'public' || (item.creator !== this.USER_ID && !this.isRootDesigner)) {
        return require('../../assets/project/modifys.png');
      } else {
        return require('../../assets/project/modifys-h.png');
      }
    },
    setDelImgSrc(item) {
      if (item.isshare === 'public' || (item.creator !== this.USER_ID && !this.isRootDesigner)) {
        return require('../../assets/project/delNote-d.png');
      } else {
        return require('../../assets/project/delNote-h.png');
      }
    },
    changeModalLoading() {
      this.updataLoading = false;
      this.$nextTick(() => {
        this.updataLoading = true;
      });
    },
    cancelUpload() {
      //this.$refs['uploadIcon'].clearFiles()
      this.formItem.filePath = null;
      this.formItem.file = null;
      this.$refs['formItem'].resetFields();
      this.showModal = false;
    },
    getFileName(name) {
      return name.substring(0, name.lastIndexOf('.'));
    },
    handleUploadIcon(file) {
      this.speed = 0;
      this.loaded = 0;
      this.progress = 0;
      this.isUpdataing = true;
      this.onlyFileName = file.name + '_' + new Date().getTime();
      let fileType = ['pcap', 'PCAP'];
      if (file) {
        if (file.size > 1024 * 1024) {
          this.fileSize = (Math.round((file.size * 100) / (1024 * 1024)) / 100).toString() + 'MB';
        } else {
          this.fileSize = (Math.round((file.size * 100) / 1024) / 100).toString() + 'KB';
        }
        //验证名称
        if (file.name) {
          let name = this.getFileName(file.name);
          // let reg = new RegExp('^[\u4E00-\u9FA5a-zA-Z0-9_ -]*$');
          let reg = new RegExp(newValidationRules);
          if (reg.test(name) || name.length > 64) {
            this.$Message.error({
              content: newValidationRulesTip('文件名',128),
              duration: 3
            });
            return false;
          }
        }
        let FileExt = file.name.replace(/.+\./, ''); //取得文件的后缀名
        if (!fileType.includes(FileExt)) {
          // 添加上传的镜像文件类型验证
          this.progressflag = false; //关闭文件上传进度展示
          this.$Message.error({ content: '请上传pcap类型的文件', duration: 5, closable: true });
          return false;
        }
        this.$refs['uploadIcon'].clearFiles();
      }
    },
    imprtQuesSucc(res) {
      if (res.code === 1) {
        this.formItem.filePath = res.data;
        this.formItem.fileId = res.info.id;
      } else {
        this.$Message.error({ content: res.message, duration: 3 });
        this.$refs['uploadIcon'].clearFiles();
      }
    },
    formBtn(name) {
      let _this = this;
      let isPublic = '';
      if (this.isAdd) {
        this.$refs[name].validate((valid) => {
          if (valid) {
            if (!this.formItem.filePath) {
              _this.$Message.warning({
                content: '请选择上传的文件！',
                duration: 2
              });
              return;
            }
            let params = {
              fileName: _this.formItem.fileName,
              filePath: _this.formItem.filePath,
              fileId: _this.formItem.fileId,
              note: _this.formItem.note
            };
            this.loading = true;
            createFlow([params]).then((res) => {
              if (res.data.code === 1) {
                this.showModal = false;
                _this.$Message.success({
                  content: '操作成功',
                  duration: 3
                });
                this.loading = false;
                this.$refs['uploadIcon'].clearFiles();
                this.showModal = false;
                _this.formItem.file = null;
                _this.formItem.filePath = null;
                this.formItem.fileId = '';
                this.FlowPage = 1;
                this.getFlowList();
              } else {
                this.loading = false;
                _this.$Message.error({
                  content: res.data.message,
                  duration: 2
                });
              }
            });
          } else {
            _this.$Message.error('请完善信息！');
          }
        });
      } else {
        this.$refs[name].validate((valid) => {
          if (valid) {
            let params = {
              fileName: _this.formItem.fileName,
              note: _this.formItem.note
            };
            this.loading = true;
            modifyFlow(params, _this.formItem.id).then((res) => {
              if (res.data.code === 1) {
                this.showModal = false;
                _this.$Message.success({
                  content: '操作成功',
                  duration: 3
                });
                this.loading = false;
                this.showModal = false;
                _this.formItem.file = null;
                _this.formItem.filePath = null;
                this.getFlowList();
              } else {
                this.loading = false;
                _this.$Message.error({
                  content: res.data.message,
                  duration: 2
                });
              }
            });
          } else {
            _this.$Message.error('请完善信息！');
          }
        });
      }
    }
  }
};
</script>
<style scoped>

</style>
